package com.xkcyy.one.controller;

import com.xkcyy.one.common.Result;
import com.xkcyy.one.entity.Script;
import com.xkcyy.one.service.ScriptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 脚本控制器
 * 
 * @author yuand
 */
@RestController
@RequestMapping("/api/scripts")
public class ScriptController {

    private final ScriptService scriptService;

    @Autowired
    public ScriptController(ScriptService scriptService) {
        this.scriptService = scriptService;
    }

    /**
     * 获取所有脚本
     *
     * @return 脚本列表
     */
    @GetMapping("/list")
    public Result<List<Script>> getAllScripts() {
        return Result.success(scriptService.getAllScripts());
    }

    /**
     * 根据用户ID获取脚本列表
     *
     * @param userId 用户ID
     * @return 脚本列表
     */
    @GetMapping("/user")
    public Result<List<Script>> getScriptsByUserId(@RequestParam Long userId) {
        return Result.success(scriptService.getScriptsByUserId(userId));
    }

    /**
     * 根据ID获取脚本
     *
     * @param id 脚本ID
     * @return 脚本信息
     */
    @GetMapping("/get")
    public Result<Script> getScriptById(@RequestParam Long id) {
        return Result.success(scriptService.getScriptById(id));
    }

    /**
     * 创建脚本
     *
     * @param script 脚本信息
     * @return 创建后的脚本信息
     */
    @PostMapping("/create")
    public Result<Script> createScript(@RequestBody Script script) {
        return Result.success(scriptService.createScript(script));
    }

    /**
     * 更新脚本
     *
     * @param id     脚本ID
     * @param script 脚本信息
     * @return 更新后的脚本信息
     */
    @PutMapping("/update")
    public Result<Script> updateScript(@RequestParam Long id, @RequestBody Script script) {
        script.setId(id);
        return Result.success(scriptService.updateScript(script));
    }

    /**
     * 删除脚本
     *
     * @param id 脚本ID
     * @return 操作结果
     */
    @DeleteMapping("/delete")
    public Result<Void> deleteScript(@RequestParam Long id) {
        scriptService.deleteScript(id);
        return Result.success();
    }

    /**
     * 编译脚本
     *
     * @param id 脚本ID
     * @return 编译后的脚本信息
     */
    @PostMapping("/compile")
    public Result<Script> compileScript(@RequestParam Long id) {
        return Result.success(scriptService.compileScript(id));
    }

    /**
     * 根据权限级别获取脚本列表
     *
     * @param level 权限级别
     * @return 脚本列表
     */
    @GetMapping("/permission")
    public Result<List<Script>> getScriptsByPermissionLevel(@RequestParam String level) {
        return Result.success(scriptService.getScriptsByPermissionLevel(level));
    }
}